package com.iot.ht.controller.htuserlogin.service;

import com.iot.core.data.BaseQto;
import com.iot.core.data.entity.HtUserLogin;
import com.iot.core.data.mapper.HtDbMapper;
import com.iot.core.data.mapper.HtUserLoginMapper;
import com.iot.core.data.service.ServiceImpl;
import com.iot.core.springboot.MyThreadLocal;
import com.iot.ht.controller.htuserlogin.data.HtUserLoginDebugDto;
import com.iot.ht.controller.htuserlogin.data.HtUserLoginQto;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import static com.iot.core.data.entity.table.HtUserLoginTableDef.HT_USER_LOGIN;

@Slf4j
@Service
public class HtUserLoginService extends ServiceImpl<HtUserLoginMapper, HtUserLogin> implements IHtUserLoginService {
    @Autowired
    HtDbMapper htdbMapper;


    @Override

    public Page<HtUserLogin> page(HtUserLoginQto qm){
        var qw=new QueryWrapper();
        if(StringUtils.hasText(qm.getState() )){
            var bIsOnline = qm.getState().equals("在线")  ;
            qw.and( HT_USER_LOGIN.ONLINE.eq(bIsOnline));
        }

        if(StringUtils.hasText(qm.getDtb() )){
            qw.and( HT_USER_LOGIN.CRT_DT.ge(qm.getDB()));
        }

        if(StringUtils.hasText(qm.getDte() )){
            qw.and( HT_USER_LOGIN.CRT_DT.lt(qm.getDE()));
        }

        if(StringUtils.hasText(qm.getKey() )){
            qw.and( HT_USER_LOGIN.NAME.like(qm.getKey())
                            .or( HT_USER_LOGIN.HTDEPT_NAME.like(qm.getKey()) )
            );

        }
        var sort=qm.getSort();
        qw.orderBy( sort.toString()  );

        var r=getMapper().page( qm,qw );
        return r;
    }

    @Override
    public int forceLx(BaseQto mm)
    {
        var m=getById(mm);
        if (m.isOnline())
        {
            m.setOnline(false);
            MyThreadLocal.get().setLogMemo(String.format("强制%s 离线",m.getName()));
            return updateById(m);
        }
        return 0;
    }

    @Override
    public int setDebug(HtUserLoginDebugDto mm)
    {
        var m=getById(mm.getId() );
        if (m.isOnline())
        {
            if (m.isDebug()!=mm.isDebug() )
            {
                m.setDebug(mm.isDebug() );
                MyThreadLocal.get().setLogMemo(String.format("设置%s 调试模式：%s",m.getName(),m.isDebug() ));
                return updateById(m);
            }
        }
        return 0;
    }

}
